<template>
  <view class="word-match-game">
    <!-- 游戏头部信息 -->
    <view class="game-header">
      <view class="score-info">
        <text class="score-label">分数</text>
        <text class="score-value">{{ score }}</text>
      </view>
      <view class="level-info">
        <text class="level-label">关卡</text>
        <text class="level-value">{{ currentLevel }}</text>
      </view>
      <view class="error-info">
        <text class="error-label">错误</text>
        <text class="error-value">{{ errors }}/{{ maxErrors }}</text>
      </view>
    </view>

    <!-- 游戏状态提示 -->
    <view class="game-status">
      <text class="status-text">点击匹配的中英文单词对</text>
      <text class="pairs-text">已匹配: {{ matchedPairs }}/{{ totalPairs }}</text>
    </view>

    <!-- 游戏棋盘 - 所有卡片都显示内容 -->
    <view class="game-board">
      <view
          v-for="(card, index) in cards"
          :key="index"
          class="card"
          :class="getCardClass(card)"
          @click="selectCard(card)"
      >
        <view class="card-content">
          <text class="card-text">{{ card.content }}</text>
          <text class="card-type">{{ card.type === 'english' ? 'EN' : 'CN' }}</text>
        </view>

        <!-- 匹配成功效果 -->
        <view v-if="card.isMatched" class="match-effect">✓</view>
      </view>
    </view>

    <!-- 选中的卡片提示 -->
    <view v-if="selectedCards.length === 1" class="selected-hint">
      <text>已选中: {{ selectedCards[0].content }}</text>
      <text>请选择对应的{{ selectedCards[0].type === 'english' ? '中文' : '英文' }}单词</text>
    </view>

    <!-- 当前选中的卡片 -->
    <view v-if="selectedCards.length > 0" class="current-selection">
      <text class="selection-title">已选卡片:</text>
      <view class="selected-cards-list">
        <view
            v-for="(card, index) in selectedCards"
            :key="index"
            class="selected-card-item"
            :class="card.type"
        >
          <text class="selected-card-text">{{ card.content }}</text>
          <text class="selected-card-type">{{ card.type === 'english' ? 'EN' : 'CN' }}</text>
        </view>
      </view>
    </view>

    <!-- 游戏控制 -->
    <view class="game-controls">
      <button class="control-btn hint-btn" @click="showHint" :disabled="!hintsAvailable || selectedCards.length > 0">
        <text class="btn-icon">💡</text>
        <text class="btn-text">提示 ({{ hintsAvailable }})</text>
      </button>

      <button class="control-btn shuffle-btn" @click="shuffleCards" :disabled="selectedCards.length > 0">
        <text class="btn-icon">🔀</text>
        <text class="btn-text">重新排列</text>
      </button>

      <button class="control-btn reset-btn" @click="resetSelection" :disabled="selectedCards.length === 0">
        <text class="btn-icon">↶</text>
        <text class="btn-text">取消选择</text>
      </button>
    </view>

    <!-- 游戏结果弹窗 -->
    <view v-if="showResult" class="result-modal">
      <view class="result-content">
        <text class="result-title">{{ gameResult === 'win' ? '🎉 恭喜过关！' : '😔 游戏结束' }}</text>

        <view class="result-stats">
          <view class="stat-item">
            <text class="stat-label">得分</text>
            <text class="stat-value">{{ score }}</text>
          </view>
          <view class="stat-item">
            <text class="stat-label">用时</text>
            <text class="stat-value">{{ formatTime(timeUsed) }}</text>
          </view>
          <view class="stat-item">
            <text class="stat-label">错误次数</text>
            <text class="stat-value">{{ errors }}</text>
          </view>
        </view>

        <view class="result-actions">
          <button class="result-btn restart-btn" @click="restartGame">
            <text>再玩一次</text>
          </button>
          <button class="result-btn next-btn" @click="nextLevel" v-if="gameResult === 'win' && currentLevel < maxLevel">
            <text>下一关</text>
          </button>
          <button class="result-btn exit-btn" @click="exitGame">
            <text>退出</text>
          </button>
        </view>
      </view>
    </view>

    <!-- 匹配成功效果 -->
    <view v-if="showMatchEffect" class="match-success-effect">
      <text class="match-text">🎯 匹配成功！+{{ matchScore }}分</text>
    </view>

    <!-- 错误提示 -->
    <view v-if="showErrorEffect" class="error-effect">
      <text class="error-text">❌ 匹配错误！错误次数: {{ errors }}</text>
    </view>
  </view>
</template>

<script>
// 单词库数据 - 中英文配对
const WORD_PAIRS = [
  // 第一关 - 基础单词 (4对)
  { english: "apple", chinese: "苹果", level: 1 },
  { english: "banana", chinese: "香蕉", level: 1 },
  { english: "cat", chinese: "猫", level: 1 },
  { english: "dog", chinese: "狗", level: 1 },

  // 第二关 - 常见单词 (6对)
  { english: "computer", chinese: "电脑", level: 2 },
  { english: "phone", chinese: "手机", level: 2 },
  { english: "water", chinese: "水", level: 2 },
  { english: "school", chinese: "学校", level: 2 },
  { english: "friend", chinese: "朋友", level: 2 },
  { english: "book", chinese: "书", level: 2 },

  // 第三关 - 进阶单词 (8对)
  { english: "environment", chinese: "环境", level: 3 },
  { english: "technology", chinese: "技术", level: 3 },
  { english: "education", chinese: "教育", level: 3 },
  { english: "communication", chinese: "沟通", level: 3 },
  { english: "development", chinese: "发展", level: 3 },
  { english: "opportunity", chinese: "机会", level: 3 },
  { english: "language", chinese: "语言", level: 3 },
  { english: "program", chinese: "程序", level: 3 }
];

export default {
  name: "WordMatchGame",
  data() {
    return {
      // 游戏状态
      score: 0,
      currentLevel: 1,
      maxLevel: 3,
      errors: 0,
      maxErrors: 5,
      timeUsed: 0,
      isPaused: false,
      gameStarted: false,
      showResult: false,
      gameResult: '', // 'win' or 'lose'

      // 卡片数据
      cards: [],
      selectedCards: [],
      matchedPairs: 0,
      totalPairs: 0,

      // 提示系统
      hintsAvailable: 3,
      showHintEffect: false,
      hintPair: {},

      // 效果显示
      showMatchEffect: false,
      showErrorEffect: false,
      matchScore: 0,

      // 游戏计时器
      gameTimer: null
    };
  },

  computed: {
    // 当前关卡可用的单词对数量
    levelPairCount() {
      return [4, 6, 8][this.currentLevel - 1] || 4;
    }
  },

  onLoad() {
    this.initGame();
  },

  onUnload() {
    this.stopGameTimer();
  },

  methods: {
    // 初始化游戏
    initGame() {
      this.generateCards();
      this.startGameTimer();
      this.gameStarted = true;
    },

    // 生成卡片
    generateCards() {
      this.cards = [];
      this.selectedCards = [];
      this.matchedPairs = 0;

      // 获取当前关卡的单词对
      const allPairs = WORD_PAIRS.filter(pair => pair.level === this.currentLevel);
      const pairs = this.shuffleArray(allPairs).slice(0, this.levelPairCount);
      this.totalPairs = pairs.length;

      // 为每个单词对生成英文和中文卡片
      pairs.forEach(pair => {
        // 英文卡片
        this.cards.push({
          id: `${pair.english}-en`,
          content: pair.english,
          pairId: pair.english,
          type: 'english',
          isMatched: false
        });

        // 中文卡片
        this.cards.push({
          id: `${pair.english}-cn`,
          content: pair.chinese,
          pairId: pair.english,
          type: 'chinese',
          isMatched: false
        });
      });

      // 洗牌
      this.shuffleCards();
    },

    // 洗牌
    shuffleCards() {
      this.cards = this.shuffleArray(this.cards);
    },

    // 选择卡片
    selectCard(card) {
      if (this.isPaused || this.showResult) return;
      if (card.isMatched) return;
      if (this.selectedCards.includes(card)) return;
      if (this.selectedCards.length >= 2) return;

      // 检查是否选择了同类型的卡片
      if (this.selectedCards.length === 1) {
        const firstCard = this.selectedCards[0];
        if (firstCard.type === card.type) {
          uni.showToast({
            title: '请选择另一种语言',
            icon: 'none',
            duration: 1000
          });
          return;
        }
      }

      // 添加选中效果
      this.selectedCards.push(card);

      // 振动反馈
      uni.vibrateShort();

      // 如果选中了两张卡片，检查是否匹配
      if (this.selectedCards.length === 2) {
        setTimeout(() => {
          this.checkMatch();
        }, 300);
      }
    },

    // 检查卡片是否匹配
    checkMatch() {
      const [card1, card2] = this.selectedCards;

      // 检查是否是同一对卡片（相同的pairId）且一个是英文一个是中文
      if (card1.pairId === card2.pairId && card1.type !== card2.type) {
        this.handleMatchSuccess(card1, card2);
      } else {
        this.handleMatchFailure(card1, card2);
      }
    },

    // 处理匹配成功
    handleMatchSuccess(card1, card2) {
      // 标记为已匹配
      card1.isMatched = true;
      card2.isMatched = true;

      // 计算得分（基于关卡）
      this.matchScore = this.currentLevel * 20;
      this.score += this.matchScore;
      this.matchedPairs++;

      // 显示匹配成功效果
      this.showMatchEffect = true;
      setTimeout(() => {
        this.showMatchEffect = false;
      }, 1500);

      // 清空选中卡片
      this.selectedCards = [];

      // 检查是否过关
      if (this.matchedPairs === this.totalPairs) {
        setTimeout(() => {
          this.endGame('win');
        }, 1000);
      }
    },

    // 处理匹配失败
    handleMatchFailure(card1, card2) {
      this.errors++;

      // 显示错误效果
      this.showErrorEffect = true;
      setTimeout(() => {
        this.showErrorEffect = false;
      }, 1500);

      // 清空选中卡片
      setTimeout(() => {
        this.selectedCards = [];
      }, 1000);

      // 检查是否超过错误限制
      if (this.errors >= this.maxErrors) {
        setTimeout(() => {
          this.endGame('lose');
        }, 500);
      }
    },

    // 重置选择
    resetSelection() {
      this.selectedCards = [];
    },

    // 获取卡片样式类
    getCardClass(card) {
      return {
        'matched': card.isMatched,
        'selected': this.selectedCards.includes(card),
        'english': card.type === 'english',
        'chinese': card.type === 'chinese'
      };
    },

    // 提示功能
    showHint() {
      if (this.hintsAvailable <= 0) return;
      if (this.selectedCards.length > 0) return;

      // 找到第一个未匹配的单词对
      const unmatchedCards = this.cards.filter(card => !card.isMatched);
      if (unmatchedCards.length === 0) return;

      const firstCard = unmatchedCards[0];
      const pairId = firstCard.pairId;
      const pairCards = this.cards.filter(card => card.pairId === pairId && !card.isMatched);

      if (pairCards.length === 2) {
        this.hintsAvailable--;

        // 高亮显示对应的两张卡片
        pairCards.forEach(card => {
          // 添加临时高亮效果
          this.$set(card, 'isHinted', true);
          setTimeout(() => {
            this.$set(card, 'isHinted', false);
          }, 2000);
        });

        uni.showToast({
          title: `提示: ${pairCards.find(c => c.type === 'english').content} - ${pairCards.find(c => c.type === 'chinese').content}`,
          icon: 'none',
          duration: 2000
        });
      }
    },

    // 下一关
    nextLevel() {
      if (this.currentLevel < this.maxLevel) {
        this.currentLevel++;
        this.errors = 0;
        this.timeUsed = 0;
        this.hintsAvailable = 3;
        this.showResult = false;
        this.generateCards();
      } else {
        uni.showToast({
          title: '恭喜！您已通关所有关卡！',
          icon: 'success'
        });
      }
    },

    // 游戏计时器
    startGameTimer() {
      this.gameTimer = setInterval(() => {
        if (!this.isPaused && this.gameStarted && !this.showResult) {
          this.timeUsed++;
        }
      }, 1000);
    },

    stopGameTimer() {
      if (this.gameTimer) {
        clearInterval(this.gameTimer);
      }
    },

    // 结束游戏
    endGame(result) {
      this.gameResult = result;
      this.showResult = true;
      this.stopGameTimer();
    },

    // 重新开始游戏
    restartGame() {
      this.showResult = false;
      this.score = 0;
      this.currentLevel = 1;
      this.errors = 0;
      this.timeUsed = 0;
      this.hintsAvailable = 3;
      this.initGame();
    },

    // 退出游戏
    exitGame() {
      uni.navigateBack();
    },

    // 工具函数
    shuffleArray(array) {
      const newArray = [...array];
      for (let i = newArray.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
      }
      return newArray;
    },

    formatTime(seconds) {
      const mins = Math.floor(seconds / 60);
      const secs = seconds % 60;
      return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    }
  }
};
</script>

<style scoped>
.word-match-game {
  padding: 20rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
}

/* 游戏头部 */
.game-header {
  display: flex;
  justify-content: space-between;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.score-info, .level-info, .error-info {
  display: flex;
  gap: 8rpx;
}

.score-label, .level-label, .error-label {
  font-size: 24rpx;
  color: #7f8c8d;
  margin-bottom: 8rpx;
}

.score-value, .level-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #2c3e50;
}

.error-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #e74c3c;
}

/* 游戏状态 */
.game-status {
  display: flex;
  justify-content: space-between;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  text-align: center;
}

.status-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #2c3e50;
  display: block;
  margin-bottom: 10rpx;
}

.pairs-text {
  font-size: 28rpx;
  color: #3498db;
}

/* 游戏棋盘 - 所有卡片都显示内容 */
.game-board {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16rpx;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.card {
  aspect-ratio: 4/3;
  background: linear-gradient(135deg, #ffffff, #f8f9fa);
  border-radius: 16rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  transition: all 0.3s ease;
  cursor: pointer;
  border: 3rpx solid #e0e0e0;
  padding: 20rpx;
}

.card.selected {
  transform: scale(1.05);
  border-width: 4rpx;
  box-shadow: 0 8rpx 25rpx rgba(0, 0, 0, 0.15);
}

.card.matched {
  opacity: 0.3;
  transform: scale(0.9);
}

.card.english {
  border-color: #3498db;
}

.card.english.selected {
  background: linear-gradient(135deg, #e3f2fd, #bbdefb);
  border-color: #1976d2;
}

.card.chinese {
  border-color: #e74c3c;
}

.card.chinese.selected {
  background: linear-gradient(135deg, #ffebee, #ffcdd2);
  border-color: #d32f2f;
}

.card.hinted {
  animation: hintPulse 2s ease-in-out;
}

.card-content {
  text-align: center;
}

.card-text {
  font-size: 28rpx;
  font-weight: bold;
  color: #2c3e50;
  display: block;
  margin-bottom: 8rpx;
}

.card-type {
  font-size: 20rpx;
  color: #7f8c8d;
  background: #f0f0f0;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.match-effect {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 60rpx;
  color: #27ae60;
  animation: matchPulse 0.6s ease-in-out;
}

@keyframes matchPulse {
  0% { transform: translate(-50%, -50%) scale(0); opacity: 0; }
  50% { transform: translate(-50%, -50%) scale(1.2); opacity: 1; }
  100% { transform: translate(-50%, -50%) scale(1); opacity: 1; }
}

@keyframes hintPulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); box-shadow: 0 0 30rpx gold; }
  100% { transform: scale(1); }
}

/* 选中提示 */
.selected-hint {
  background: rgba(52, 152, 219, 0.1);
  border: 2rpx solid #3498db;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  text-align: center;
}

.selected-hint text {
  display: block;
  font-size: 28rpx;
  color: #3498db;
  margin-bottom: 8rpx;
}

.selected-hint text:last-child {
  color: #7f8c8d;
  font-size: 24rpx;
}

/* 当前选中的卡片 */
.current-selection {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.selection-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #2c3e50;
  display: block;
  margin-bottom: 16rpx;
}

.selected-cards-list {
  display: flex;
  gap: 16rpx;
}

.selected-card-item {
  flex: 1;
  padding: 20rpx;
  border-radius: 12rpx;
  text-align: center;
}

.selected-card-item.english {
  background: #e3f2fd;
  border: 2rpx solid #3498db;
}

.selected-card-item.chinese {
  background: #ffebee;
  border: 2rpx solid #e74c3c;
}

.selected-card-text {
  font-size: 24rpx;
  font-weight: bold;
  color: #2c3e50;
  display: block;
  margin-bottom: 8rpx;
}

.selected-card-type {
  font-size: 18rpx;
  color: #7f8c8d;
  background: rgba(255, 255, 255, 0.7);
  padding: 2rpx 8rpx;
  border-radius: 10rpx;
}

/* 游戏控制 */
.game-controls {
  display: flex;
  gap: 16rpx;
  margin-bottom: 20rpx;
}

.control-btn {
  flex: 1;
  background: linear-gradient(135deg, #3498db, #2980b9);
  color: white;
  border: none;
  border-radius: 16rpx;
  padding: 20rpx;
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.control-btn:disabled {
  opacity: 0.6;
}

.hint-btn {
  background: linear-gradient(135deg, #f39c12, #d35400);
}

.shuffle-btn {
  background: linear-gradient(135deg, #9b59b6, #8e44ad);
}

.reset-btn {
  background: linear-gradient(135deg, #95a5a6, #7f8c8d);
}

.btn-icon {
  font-size: 40rpx;
}

.btn-text {
  font-size: 24rpx;
}

/* 结果弹窗 */
.result-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.result-content {
  background: white;
  border-radius: 30rpx;
  padding: 60rpx 40rpx;
  text-align: center;
  width: 80%;
}

.result-title {
  font-size: 48rpx;
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 40rpx;
  display: block;
}

.result-stats {
  display: flex;
  justify-content: space-around;
  margin-bottom: 40rpx;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-label {
  font-size: 24rpx;
  color: #7f8c8d;
  margin-bottom: 8rpx;
}

.stat-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #3498db;
}

.result-actions {
  display: flex;
  gap: 20rpx;
}

.result-btn {
  flex: 1;
  padding: 20rpx;
  border: none;
  border-radius: 16rpx;
  color: white;
  font-size: 28rpx;
}

.restart-btn {
  background: #3498db;
}

.next-btn {
  background: #27ae60;
}

.exit-btn {
  background: #95a5a6;
}

/* 效果提示 */
.match-success-effect {
  position: fixed;
  top: 30%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(39, 174, 96, 0.95);
  color: white;
  padding: 30rpx 60rpx;
  border-radius: 50rpx;
  font-size: 36rpx;
  font-weight: bold;
  z-index: 999;
  animation: matchSuccess 1.5s ease-in-out;
}

.error-effect {
  position: fixed;
  top: 30%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(231, 76, 60, 0.95);
  color: white;
  padding: 30rpx 60rpx;
  border-radius: 50rpx;
  font-size: 36rpx;
  font-weight: bold;
  z-index: 999;
  animation: errorShake 1.5s ease-in-out;
}

@keyframes matchSuccess {
  0% { transform: translate(-50%, -50%) scale(0.8); opacity: 0; }
  50% { transform: translate(-50%, -50%) scale(1.1); opacity: 1; }
  100% { transform: translate(-50%, -50%) scale(1); opacity: 0; }
}

@keyframes errorShake {
  0%, 100% { transform: translate(-50%, -50%); }
  25% { transform: translate(-55%, -50%); }
  75% { transform: translate(-45%, -50%); }
}

/* 响应式设计 */
@media (max-width: 750px) {
  .game-header {
    gap: 20rpx;
  }

  .game-board {
    grid-template-columns: repeat(2, 1fr);
  }

  .result-actions {
    flex-direction: column;
  }

  .card-text {
    font-size: 24rpx;
  }

  .selected-cards-list {
    flex-direction: column;
  }
}
</style>
